package cn.fetosoft.woodpecker.core.scheduled;

import cn.fetosoft.commons.scheduled.TaskInfo;
import cn.fetosoft.commons.scheduled.TaskListener;
import cn.fetosoft.woodpecker.core.data.entity.Scheduled;
import cn.fetosoft.woodpecker.core.data.service.ScheduledService;
import cn.fetosoft.woodpecker.core.enums.ScheduledStatus;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 任务启停监听器
 * @author guobingbing
 * @version 1.0
 * @wechat t_gbinb
 * @create 2021/7/27 17:29
 */
@Component
public class ScheduledListener implements TaskListener {

	private static final Logger logger = LoggerFactory.getLogger(ScheduledListener.class);
	@Autowired
	private ScheduledService scheduledService;

	@Override
	public void start(TaskInfo taskInfo, SchedulerException e) {
		this.updateScheduledStatus(ScheduledStatus.Running, taskInfo.getCode(), e);
	}

	@Override
	public void stop(TaskInfo taskInfo, SchedulerException e) {
		this.updateScheduledStatus(ScheduledStatus.Stop, taskInfo.getCode(), e);
	}

	private void updateScheduledStatus(ScheduledStatus scheduledStatus, String sid, SchedulerException e){
		Scheduled scheduled = scheduledService.findById(sid, Scheduled.class);
		Scheduled updateScheduled = new Scheduled();
		updateScheduled.setId(scheduled.getId());
		updateScheduled.setStatus(scheduledStatus.getValue());
		if(scheduledStatus==ScheduledStatus.Running) {
			updateScheduled.setStartTime(System.currentTimeMillis());
		}else{
			updateScheduled.setStopTime(System.currentTimeMillis());
		}
		if(e!=null){
			String msg = e.getMessage();
			if(msg.length()<300){
				updateScheduled.setErrorMsg(msg);
			}else{
				updateScheduled.setErrorMsg(msg.substring(0,300));
			}
		}
		try {
			scheduledService.update(updateScheduled);
		} catch (Exception ex) {
			logger.error("updateScheduledStatus", ex);
		}
	}
}
